package com.lienlq.voicemusic.ui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.lienlq.voicemusic.R;
import com.lienlq.voicemusic.entity.MusicService;
import com.lienlq.voicemusic.entity.Track;
import com.lienlq.voicemusic.entity.TrackAdapter;
import com.lienlq.voicemusic.xmlprc.XMLRPCMethod;
import com.lienlq.voicemusic.xmlprc.XMLRPCMethodCallback;

public class TrackFragment extends Fragment  {
	
	private JSONObject JSobject = null;
	private JSONArray jsArray;
	
		  private ListView list = null;
		  private ArrayList<Track> trackList = new ArrayList<Track>(); 
		 
		  Messenger mService = null; 
		  private int currentTrack = 0;
		  private boolean isBound = false;

		 
		 
		 
		private void sendDataToService() {
			Message msg = Message.obtain(null, MusicService.MSG_RECIEVED_TRACK_LIST );
			Bundle b = new Bundle();
        	b.putParcelableArrayList(MusicService.TRACK_LIST_NAME, trackList);
    		b.putInt(MusicService.PLAYING_TRACK, currentTrack);
    		msg.setData(b);
    		try {
				mService.send(msg);
			} catch (RemoteException e) {  
				Log.e("SERVICE", e.toString());
			}
		}
			
			private ServiceConnection serviceConnection = new ServiceConnection() {
				
				@Override
				public void onServiceDisconnected(ComponentName name) {  
					mService = null; 
					isBound = false;
				}
				
				@Override
				public void onServiceConnected(ComponentName name, IBinder service) { 
					 isBound = true;
					 mService = new Messenger(service);
					 
				}
			};
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);  
	        //loadContent();  
	        XMLRPCMethod method=new XMLRPCMethod("selecthotSong",new XMLRPCMethodCallback() {
				
				@Override
				public void CallFinished(Object result) {
					// TODO Auto-generated method stub
					try{
						JSobject = new JSONObject(result.toString());
						jsArray = JSobject.getJSONArray("songlist");
						
//						Log.i("KETQUA",result.toString());
							
							for(int i=0;i<jsArray.length();i++)
							{
								JSONObject obj=jsArray.getJSONObject(i);
								Track track=new Track(obj.getString("songname").trim(),"Unknow Albuml",
										obj.getString("artistname"),obj.getString("composer"),
										obj.getString("songlink"),obj.getString("songimg"),obj.getInt("hit"));
								trackList.add(track);
							}
							 list.setAdapter(new TrackAdapter(getActivity(), R.layout.item_track, 
						        		trackList));

					}catch(Exception e){
						Log.w("Error",e.toString());
					}
				}
			});
	    	
	    	Object[] params = null;
	    	method.call(params);
	        doBindService();
	    }
	    
	    @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	    	View v = inflater.inflate(R.layout.fragment_hotest, container, false);
	        list = (ListView)v.findViewById(R.id.songs_list_fragment_hotest);
	       
	       	        list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {  
					currentTrack = arg2; 
					sendDataToService(); 
				}
			});
	        
	        return v;
	    }
	    
	    
	    @Override
	    public void onStop() { 
	    	super.onStop();
	    	doUnbindService();
	    }
	    
		private void doBindService() {
			if (MusicService.isRunning) {
				Intent intent = new Intent(getActivity().getBaseContext(), MusicService.class);
				if (!getActivity().bindService(intent, serviceConnection,  Context.BIND_AUTO_CREATE)) {
					Log.e("SERVICE", "don't bind Service");
				}
			}
		}
	    
		private void doUnbindService() {
			 if (isBound) {
				 getActivity().unbindService(serviceConnection);
				 isBound = false;
			 }
		}
		
		
		  private void loadContent() {
			    /*	for(int i = 0; i<5; i++)  {
			    		trackList.add(new Track("Just Give Me A Result", "Unknow Album", "Pink ft. Le Quang Lien", "Unknown Musician", trackUri, MusicSample.avatarUri, 53689));
				        trackList.add(new Track("Stay",  "Unapologetic (Deluxe Edition)" , "Stay-Rihanna ft. Mikky Ekko", "unknown",trackUri2,MusicSample.avatarUri2,  49365));
			    	}*/
			    	
			    } 
}
